﻿using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using ST.Common.Util;
using ST.WX.Common.Model;
using System;
using System.Collections.Generic;
using System.Text;

namespace ST.WX.Common
{
	public class WXAccessTokenManager
	{
		private readonly IMemoryCache cache;
		private readonly string CACHE_KEY_PREFIX = "ACCESS_TOKEN_";
		private readonly ILogger logger;

		public WXAccessTokenManager(IMemoryCache _cache, ILogger<WXAccessTokenManager> _logger)
		{
			cache = _cache;
			logger = _logger;
		}

		/// <summary>
		/// 刷新ACCESS_TOKEN
		/// </summary>
		public bool RefreshAccessToken(string appID, string appSecret)
		{
			try
			{
				if (string.IsNullOrEmpty(appID))
				{
					throw new WXException("appID不能为空");
				}
				string cacheKey = CACHE_KEY_PREFIX + appID;
				string respText = HttpHelper.Get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appID + "&secret=" + appSecret);
				if (string.IsNullOrEmpty(respText))
				{
					throw new WXException("刷新ACCESS_TOKEN返回为空");
				}
				var ret = Newtonsoft.Json.JsonConvert.DeserializeObject<WXTokenResult>(respText);
				if (string.IsNullOrWhiteSpace(ret.access_token))
				{
					throw new WXException($"刷新ACCESS_TOKEN返回错误码：{ret.errcode}，错误消息：{ret.errmsg}");
				}

				MemoryCacheEntryOptions opts = new MemoryCacheEntryOptions();
				opts.AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(ret.expires_in);
				//opts.AbsoluteExpiration = DateTime.SpecifyKind(DateTime.Now.AddSeconds(ret.expires_in), DateTimeKind.Local);//微信官方7200秒过期
				cache.Set(cacheKey, ret.access_token, opts);
				return true;
			}
			catch (WXException ex)
			{
				logger.LogError(ex.InnerException ?? ex, "刷新ACCESS_TOKEN出错");
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, "刷新ACCESS_TOKEN出错");
			}
			return false;
		}

		/// <summary>
		/// 获取ACCESS_TOKEN
		/// </summary>
		public string GetAccessToken(string appID, string appSecret)
		{
			try
			{
				if (string.IsNullOrEmpty(appID))
				{
					throw new WXException("appID不能为空");
				}
				string cacheKey = CACHE_KEY_PREFIX + appID;
				object retCache = cache.Get(cacheKey);
				if (retCache != null)
				{
					return (string)retCache;
				}
				else
				{
					string accessToken = string.Empty;
					string respText = HttpHelper.Get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appID + "&secret=" + appSecret);
					if (string.IsNullOrWhiteSpace(respText))
					{
						throw new Exception("获取ACCESS_TOKEN返回为空");
					}
					var ret = Newtonsoft.Json.JsonConvert.DeserializeObject<WXTokenResult>(respText);
					accessToken = ret.access_token;
					if (string.IsNullOrWhiteSpace(accessToken))
					{
						throw new Exception($"获取ACCESS_TOKEN返回错误码：{ret.errcode}，错误消息：{ret.errmsg}");
					}
					MemoryCacheEntryOptions opts = new MemoryCacheEntryOptions();
					opts.AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(ret.expires_in);
					//opts.AbsoluteExpiration = DateTime.SpecifyKind(DateTime.Now.AddSeconds(ret.expires_in), DateTimeKind.Local);//微信官方7200秒过期
					cache.Set(CACHE_KEY_PREFIX + appID, accessToken, opts);

					return accessToken;
				}
			}
			catch (WXException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
			}
			return string.Empty;
		}
	}
}
